import React from 'react';
import {
  Row,
  Col,
  Tree,
  Select,
  Button,
  Input,
  Form,
  DatePicker,
  Spin,
  Table,
  Pagination,
  TreeSelect,
  message,
  Modal
} from 'antd';
const { confirm } = Modal;
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  SyncOutlined,
  UserOutlined,
  CloseOutlined,
} from '@ant-design/icons';
// import { Page } from 'components'
import styles from './index.less';
import { connect } from 'dva';

import AddModal from './addModal';
import RoleModal from './roleModal';
import SelectModal from './selectModal';
import { PageHeaderWrapper } from '@ant-design/pro-layout';

import defaultSettings from '../../../../config/defaultSettings'

const { Search } = Input;

@Form.create()
@connect(({ system }) => ({ ...system }))
class Index extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currUsername: '',
      currOrgName: '',
      currTellphone: '',
      currStatus: '',
      currType: '',
      timestamp: '',
      checkColumns: [
        { title: '用户名称', dataIndex: 'staffName', key: 'staffName' },
        { title: '用户账号', dataIndex: 'loginName', key: 'loginName' },
        { title: '手机号码', dataIndex: 'telephone', key: 'telephone' },
        {
          title: '用户角色',
          dataIndex: 'yhjs',
          key: 'yhjs',
          render: (text, record) => (
            <a onClick={() => this.roleManage(record)} className={styles.iconBg}>
              <UserOutlined />
            </a>
          ),
        },
        {
          //1:在用  2:删除  3:离职  4:冻结
          title: '状态',
          dataIndex: 'statusCdDesc',
          key: 'statusCdDesc',
          render: (text, record) => (
            <span style={{ color: record.statusCd == 1 ? 'green' : 'red' }}>{text}</span>
          ),
        },
        { title: '归属部门', dataIndex: 'orgName', key: 'orgName' },
        { title: '创建时间', dataIndex: 'createdDt', key: 'createdDt' },
        {
          title: '操作',
          dataIndex: 'cz',
          width: 200,
          render: (text, record) => (
            <p className={styles.tableBtns}>
              <a onClick={() => this.updateData(record)}>
                <EditOutlined />
                修改
              </a>
              <a onClick={() => this.resetPwdFun(record)}>
                <SyncOutlined />
                重置
              </a>
              <a onClick={() => this.deleteData(record)}>
                <CloseOutlined />
                删除
              </a>
            </p>
          ),
        },
      ],
      dataList: [],
      orgList: [],
      treeLoadingData: [],
      currParentId: 0,
      totalPage: 1,
      pageSize: 10,
      totalData: 3,
      currentPage: 1,
      loading: false,
      selectedRowKeys: [],
      value: undefined,
      treeData: [
        { id: 1, pId: 0, value: '123', title: 'Expand to load' },
        { id: 2, pId: 0, value: '456', title: 'Expand to load' },
        { id: 3, pId: 0, value: '789', title: 'Tree Node', isLeaf: true },
      ],
      addModalVisible: false,
      addTimestamp: Date.parse(new Date()),
      addLoading: false,
      // pwdTypeList: [], //密码变更周期

      roleTimestamp: Date.parse(new Date()),
      roleModalVisible: false,
      roleLoading: false,
      userDetail: {}, //当前用户详情
      roleManList: [],
      currRoleName: '',
      pwdVisible: false,
      currPwdTitle: '',
      resetPwdLoading: false,

      systemNameList: [],
      currSystemId: '',

      selectModalVisible: false,
      selectLoading: false,
    };
  }

  componentDidMount() {
    this.init();
  }

  init = () => {
    this.querySystemNameList()
  };

  querySystemNameList = async () => {
    const { props } = this;
    await props
      .dispatch({
        type: 'system/systemNameListPost',
        payload: {
          page: 1,
          rows: 20,
        },
      })
      .then(res => {
        this.setState({
          systemNameList: res.list ? res.list : [],
          currSystemId: (defaultSettings.systemId&&defaultSettings.systemId!='')?defaultSettings.systemId: (res.list? res.list[0].systemId : ''),
        },()=>{
          this.querySever();
          this.queryDeptSever()
        });
      });
  };

  //获取用户列表
  querySever = async () => {
    this.setState({ loading: true });
    const { props } = this;
    await props
      .dispatch({
        type: 'system/queryUserList',
        payload: {
          dir: 'desc',
          loginName: this.state.currUsername,
          orgName: this.state.currOrgName,
          page: this.state.currentPage,
          rows: this.state.pageSize,
          staffName: '',
          staffType: this.state.currType,
          statusCd: this.state.currStatus,
          telephone: this.state.currTellphone,
          systemId: this.state.currSystemId
        },
      })
      .then(res => {
        this.setState({
          loading: false,
          dataList: res.list ? res.list : [],
          totalData: res.total,
        });
        console.log(res, 'res');
      });
  };

  //获取部门列表
  queryDeptSever = () => {
    const { props } = this;
    props.dispatch({
        type: 'system/queryDeptList',
        payload: {
          orgName: '',
          systemId: this.state.currSystemId,
          parentId: this.state.currParentId
        },
      })
      .then(res => {
        for(let i=0;i<res.length;i++){
          res[i].value = res[i].name
          res[i].title = res[i].name
        }
        this.setState({
          orgList: res?res:[],
        });
        console.log(this.state.orgList, 'haha');
      });
  };


  onSelect = (selectedKeys, info) => {
    console.log('selected', selectedKeys, info);
  };

  //用户名称修改
  usernameChange = e => {
    this.setState({
      currUsername: e.target.value,
    });
  };

  //手机号码修改
  tellphoneChange = e => {
    this.setState({
      currTellphone: e.target.value,
    });
  };

  //状态修改
  statusChange = value => {
    this.setState({
      currStatus: value,
    });
  };

  //类型修改
  typeChange = value => {
    this.setState({
      currType: value,
    });
  };

  //提交订单
  submitFun = () => {
    this.init();
  };

  //重置
  resetFun = () => {
    this.setState(
      {
        currUsername: '',
        currOrgName: '',
        currTellphone: '',
        currStatus: '',
        currType: '',
        timestamp: Date.parse(new Date()) + 1,
      },
      () => {
        this.init();
      },
    );
  };

  //修改信息
  updateData = record => {
    // this.queryPwdChangeServer();
    this.setState({
      userDetail: record,
      addModalVisible: true,
      addTimestamp: Date.parse(new Date()) + 1,
      currParentId: 0,
    },()=>{
      this.queryDeptSever()
    });
  };

  //重置密码
  resetPwdFun = record =>{
    this.props.form.resetFields()
    this.setState({
      pwdVisible: true,
      currPwdTitle: `重置【${record.staffName}】密码`,
      userDetail: record
    })
  }

  //删除信息
  deleteData = record => {
    const _this = this;
    confirm({
      // icon: <ExclamationCircleOutlined />,
      content: `确认删除【${record.staffName}】?`,
      onOk() {
        console.log('OK');
        const { dispatch } = _this.props;
        dispatch({
          type: 'system/deleteUserPost',
          payload: {
            staffId: record.staffId
          },
        }).then(res => {
          if(res.success){
            if (res.code == 0) {
              message.success('删除成功！');
            } else {
              message.error(res.msg);
            }
            _this.init()
          }else {
            message.error(res.msg);
          }
        });
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  pwdHandleOk = () =>{
    const { validateFields, getFieldsValue } = this.props.form;
    let _this = this;
    validateFields(errors => {
      if (errors) {
        return;
      }
      const data = { ...getFieldsValue() };
      _this.setState(
        {
          resetPwdLoading: true,
        },
        () => {
          const { dispatch } = _this.props;
          const payload = Object.assign({},data,{staffId: _this.state.userDetail.staffId})
          dispatch({
            type: 'system/resetPwdPost',
            payload: payload,
          }).then(res => {
            if(res.success){
              if (res.code == 0) {
                message.success('重置成功！');
              } else {
                message.error(res.msg);
              }
              _this.setState(
                {
                  resetPwdLoading: false,
                  pwdVisible: false,
                },
                () => {
                  _this.init();
                },
              );
            }else {
              message.error(res.msg);
            }
          });
        },
      );
    });
  }

  pwdHandleCancel = () =>{
    this.setState({
      pwdVisible: false
    })
  }
  // onSelectChange = selectedRowKeys => {
  //   console.log('selectedRowKeys changed: ', selectedRowKeys);
  //   this.setState({ selectedRowKeys });
  // };

  // genTreeNode = (parentId, isLeaf = false) => {
  //   const random = Math.random()
  //     .toString(36)
  //     .substring(2, 6);
  //   return {
  //     id: random,
  //     pId: parentId,
  //     value: random,
  //     title: isLeaf ? 'Tree Node' : 'Expand to load',
  //     isLeaf,
  //   };
  // };

  onLoadData = treeNode => 
    new Promise(resolve => {
      if (treeNode.props.children) {
        resolve();
        return;
      }
      setTimeout(() => {
        const { id } = treeNode.props;
        this.setState({
          currParentId: treeNode.props.id
        },()=>{
          const { props } = this;
          props.dispatch({
            type: 'system/queryDeptList',
            payload: {
              orgName: '',
              systemId: this.state.currSystemId,
              parentId: id
            },
          })
          .then(res => {
            for(let i=0;i<res.length;i++){
              res[i].value = res[i].name
              res[i].title = res[i].name
              res[i].pId = res[i].pid
            }
            treeNode.props.dataRef.children = res;
            this.setState({
              orgList: [...this.state.orgList]
              // orgList: this.state.orgList.concat(res)
            })
          });
        })
        resolve();
      }, 1000);
    });

  onLoadSelectData = treeNode =>
    new Promise(resolve => {
      const { id } = treeNode.props;
      setTimeout(() => {
        this.setState({
          currParentId: treeNode.props.id
        },()=>{
          const { props } = this;
          props.dispatch({
            type: 'system/queryDeptList',
            payload: {
              orgName: '',
              systemId: this.state.currSystemId,
              parentId: id
            },
          })
          .then(res => {
            for(let i=0;i<res.length;i++){
              res[i].value = res[i].name
              res[i].title = res[i].name
              res[i].pId = res[i].pid
            }
            this.setState({
              orgList: this.state.orgList.concat(res)
            })
          });
        })
        resolve();
      }, 300);
    });

  orgNameChange = value => {
    console.log(value);
    this.setState({
      currOrgName: value,
    });
  };

  pageChange = page => {
    this.setState(
      {
        currentPage: page,
      },
      () => {
        this.init();
      },
    );
  };

  get addModalProps() {
    const { addModalVisible, userDetail, systemNameList, addLoading, pwdTypeList, orgList } = this.state;
    let _this = this;
    return {
      title: '用户管理',
      visible: addModalVisible,
      userDetail: userDetail,
      systemNameList: systemNameList,
      loading: addLoading,
      orgList: orgList,
      // pwdTypeList: pwdTypeList,
      width: '700px',
      onLoad: this.onLoadSelectData,
      okText: '提交',
      cancelText: '取消',
      loadDept: (data) =>{
        _this.setState({
          currSystemId: data,
          currParentId: 0
        },()=>{
          _this.queryDeptSever()
        })
      },
      onOk: data => {
        _this.setState(
          {
            loading: true,
          },
          () => {
            const { dispatch } = _this.props;
            dispatch({
              type: data.staffId==''?'system/addUser':'system/editUser',
              payload: data,
            }).then(res => {
              if(res.success){
                if (res.code == 0) {
                  message.success(data.staffId==''?'新增成功！':'修改成功！');
                } else {
                  message.error(res.msg);
                }
                _this.setState(
                  {
                    loading: false,
                    addModalVisible: false,
                  },
                  () => {
                    _this.init();
                  },
                );
              }else {
                message.error(res.msg);
              }
            });
          },
        );
      },
      onCancel() {
        _this.setState({
          addModalVisible: false,
        });
      },
    };
  }

  roleManage = record => {
    this.setState(
      {
        userDetail: record,
        // currStaffId: record.staffId,
        roleModalVisible: true,
      },
      () => {
        // this.queryRoleManSever();
      },
    );
  };

  get roleModalProps() {
    const { roleModalVisible, userDetail, roleLoading } = this.state;
    console.log(userDetail,'userDetail')
    let _this = this;
    return {
      title: `【${userDetail.staffName}】用户角色配置`,
      visible: roleModalVisible,
      userDetail: userDetail,
      // roleManList: roleManList,
      loading: roleLoading,
      // pwdTypeList: pwdTypeList,
      width: '810px',
      okText: '提交',
      cancelText: '取消',
      onOk: data => {
        _this.setState(
          {
            loading: true,
          },
          () => {
            const { dispatch } = _this.props;
            dispatch({
              type: 'system/addUser',
              payload: data,
            }).then(res => {
              if (res.statusCode == 200) {
                if (res.status == 0) {
                  message.success('新增成功！');
                } else {
                  message.error(res.message);
                }
              } else {
                message.error(res.message);
              }
              _this.setState(
                {
                  loading: false,
                  addModalVisible: false,
                },
                () => {
                  _this.init();
                },
              );
            });
          },
        );
      },
      onCancel() {
        _this.setState({
          roleModalVisible: false,
        });
      },
      queryFun(staffId, roleName) {
        _this.setState(
          {
            currStaffId: staffId,
            currRoleName: roleName,
          },
          () => {
            // _this.queryRoleManSever();
          },
        );
      },
    };
  }

  get selectModalProps() {
    const { selectModalVisible,systemNameList, orgList, selectLoading } = this.state;
    let _this = this;
    return {
      title: `部门机构选择`,
      visible: selectModalVisible,
      systemNameList: systemNameList,
      // roleManList: roleManList,
      loading: selectLoading,
      onLoad: this.onLoadData,
      orgList: orgList,
      // pwdTypeList: pwdTypeList,
      width: '810px',
      okText: '提交',
      cancelText: '取消',
      loadDept: (data) =>{
        _this.setState({
          currSystemId: data,
          currParentId: 0
        },()=>{
          _this.queryDeptSever()
        })
      },
      onOk: data => {
        _this.setState({
          currOrgName: data,
          selectModalVisible: false,
        })
      },
      onCancel() {
        _this.setState({
          selectModalVisible: false,
        });
      }
    };
  }

  //新增用户
  addFun = () => {
    const { pwdTypeList } = this.state;
    // this.queryPwdChangeServer();
    this.setState({
      userDetail: {
        staffId: '',
        // pwChgType: pwdTypeList && pwdTypeList.length > 0 ? pwdTypeList[0].pwChgTypeId : '',
        loginName: '',
        password: '',
        // staffCode: '',
        staffName: '',
        telephone: '',
        statusCd: '',
        staffExpDt: '',
        remark: '',
        // ...this.state.userDetail,
      },
      addModalVisible: true,
      addTimestamp: Date.parse(new Date()) + 1,
      currParentId: 0
    },()=>{
      this.queryDeptSever()
    });
  };

  onSelectDept = () => {
    this.setState({
      selectModalVisible: true
    })
  }

  render() {
    const { checkColumns, orgList, dataList, addTimestamp, roleTimestamp, timestamp } = this.state;
    // const { treeData } = this.state;

    const { getFieldDecorator } = this.props.form;

    // const rowSelection = {
    //   selectedRowKeys,
    //   onChange: this.onSelectChange,
    // };
    return (
      <PageHeaderWrapper title={false} breadcrumb={false}>
      <div className={styles.mainPage}>
        <Row>
          <Col span={24}>
            <dl key={timestamp+1}>
              <dt>
                <Form name="horizontal_search" layout="inline">
                  <Form.Item name="username" label="用户账号">
                    <Input
                      style={{ width: 200 }}
                      type="text"
                      placeholder="请输入用户名称"
                      defaultValue={this.state.currUsername}
                      onChange={this.usernameChange}
                    />
                  </Form.Item>
                  <Form.Item name="username" label="归属部门">
                    <Search value={this.state.currOrgName} placeholder="请选择部门" onSearch={this.onSelectDept} enterButton="选择" />
                    {/* <TreeSelect
                      allowClear
                      treeDataSimpleMode
                      style={{ width: 200 }}
                      initValue={this.state.currOrgName}
                      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                      placeholder="请选择归属部门"
                      onChange={this.orgNameChange}
                      loadData={this.onLoadData}
                      treeData={orgList}
                    /> */}
                  </Form.Item>
                  <Form.Item name="tellphone" label="手机号码">
                    <Input
                      style={{ width: 200 }}
                      type="text"
                      placeholder="请输入手机号码"
                      defaultValue={this.state.currTellphone}
                      onChange={this.tellphoneChange}
                    />
                  </Form.Item>
                  <Form.Item name="status" label="有效状态">
                    <Select
                      style={{ width: 200 }}
                      placeholder="请选择状态"
                      onChange={this.statusChange}
                      value={this.state.currStatus}
                    >
                      <Option value="">全部</Option>
                      <Option value="1">在用</Option>
                      <Option value="2">删除</Option>
                      <Option value="3">离职</Option>
                      <Option value="4">冻结</Option>
                    </Select>
                  </Form.Item>
                  <Form.Item name="status" label="用户类型">
                    <Select
                      style={{ width: 200 }}
                      placeholder="请选择用户类型"
                      onChange={this.typeChange}
                      value={this.state.currType}
                    >
                      <Option value="">全部</Option>
                      {/* {areaList.map((item,index)=>{
                            return(<Option value={item.areaName} key={index}>{item.areaName}</Option>)
                        })} */}
                    </Select>
                  </Form.Item>
                  {/* <Form.Item
                        name="createdTime"
                        label="创建时间"
                    >
                        <RangePicker />
                    </Form.Item> */}
                  <Form.Item>
                    <Button type="primary" onClick={this.submitFun}>
                      <SearchOutlined />
                      搜索
                    </Button>
                    <Button style={{ marginLeft: '8px' }} onClick={this.resetFun}>
                      <SyncOutlined />
                      重置
                    </Button>
                  </Form.Item>
                  <Form.Item style={{ float: 'right', marginRight: 0 }}>
                    <Button type="primary" onClick={this.addFun}>
                      <PlusOutlined />
                      新增
                    </Button>
                  </Form.Item>
                </Form>
              </dt>
              <dd>
                <AddModal key={addTimestamp} {...this.addModalProps} />
                <RoleModal key={roleTimestamp} {...this.roleModalProps} />
                <SelectModal {...this.selectModalProps} />
                <Modal
                  title={this.state.currPwdTitle}
                  visible={this.state.pwdVisible}
                  okText="确认重置"
                  cancelText="取消"
                  onOk={this.pwdHandleOk}
                  onCancel={this.pwdHandleCancel}
                >
                  <Spin spinning={this.state.resetPwdLoading}>
                    <Form name="horizontal" layout="inline">
                      <Form.Item label="输入密码" name="password">
                        {getFieldDecorator('password', {
                          initialValue: '',
                          rules: [
                            {
                              required: true,
                              message: '请输入重置密码',
                            },
                          ],
                        })(<Input.Password placeholder="请输入重置密码" />)}
                      </Form.Item>
                    </Form>
                  </Spin>
                </Modal>
                <Spin spinning={this.state.loading} delay={500}>
                  <Table
                    style={{ marginTop: '20px' }}
                    bordered
                    columns={checkColumns}
                    dataSource={dataList}
                    simple
                    // scroll={{ x: 1200 }}
                    pagination={false}
                    // rowSelection={rowSelection}
                  />
                </Spin>
                <p style={{ textAlign: 'center', marginTop: '20px' }}>
                  <Pagination
                    current={this.state.currentPage}
                    pageSize={this.state.pageSize}
                    total={this.state.totalData}
                    onChange={this.pageChange}
                  />
                </p>
              </dd>
            </dl>
          </Col>
        </Row>
      </div>
      </PageHeaderWrapper>
    );
  }
}

export default Index;
